const Service = require('egg').Service;
const BigNumber = require('bignumber.js');
// 前段订单列表
const listRule = {
    userAddress: {type: 'string'}
};

function toInt(str) {
    if (typeof str === 'number') return str;
    if (!str) return str;
    return parseInt(str, 10) || 0;
}

// 前段买涨买跌统计
const isBuyCountRule = {
    openTime: {type: 'string'},
    closeTime: {type: 'string'},
}

class ActionService extends Service {

    async index() {
        const ctx = this.ctx;
        ctx.validate(listRule, ctx.query);
        // 首先Account查id 根据 id查Action下关联的account_id(因为一对多没办法分页)
        let accountRow = await ctx.model.Account.findOne({
            where: {
                userAddress: ctx.query.userAddress
            },
            
        });
        // 
        if(!accountRow) {
            ctx.status = 422;
            ctx.body = { 'status_code':422, 'msg': '您是非法用户,请联系我们！'};
            return; 
        }
        
        let accountRowId = accountRow.id;
        
        let limit = toInt(ctx.query.limit) ? toInt(ctx.query.limit) : this.config.page.limit;
        let offset = toInt(ctx.query.offset) ? toInt(ctx.query.offset) : this.config.page.offset;
        offset = (offset - 1) * limit
        const query = {
            limit: limit,
            offset: offset,
            where: {
                accountId: accountRowId,
                isBuy: {
                    $ne: ''
                },
               
                isBuy: [0,1],
            },
            order: [
                ['userTimeStamp','desc']
            ]
        };
        const query_total = {
            where: {
                accountId: accountRowId,
                isBuy: {
                    $ne: ''
                },
               
                isBuy: [0,1]
            },
        };
        const total = await ctx.model.Action.findAll(query_total);
        
        const data = await ctx.model.Action.findAll(query); // Account
        return  { 'status_code': 200, 'total': total.length, 'data': data };
        ctx.status = 200;
        ctx.body = { 'status_code': 200, 'total': total.length, 'data': data };
    }

    async blockedBalance() {
        const ctx = this.ctx;
        let ifFail = 0; // 没有发送给合约 理想状态 没有出错的情况下 1 成功 2 失败
        // 
        const accountRow = await ctx.model.Account.findOne({
            where: {
                userAddress: ctx.query.userAddress,
            }
        });
        
        if(!accountRow) {
            return { 'status_code': 422, 'msg': '用户不存在！' };
        }
        const actionAccoountId = accountRow.id;
        const query_blockedAmountCount = {
            where: {
                ifFail: ifFail,
                accountId: actionAccoountId
            },
        };
        const data = await ctx.model.Action.findAll(query_blockedAmountCount); 
        let blockedMoney = 0;
        data.forEach(async function (row) {
            // 冻结
            blockedMoney = new BigNumber(blockedMoney).plus(new BigNumber(row.amount));// row.amount
        });
        // 可用
        let balance = new BigNumber(accountRow.balance).minus(new BigNumber(accountRow.freezeBalance));
        return { 'status_code': 200, 'blocked': blockedMoney, 'blance': balance };
    }

    async isBuyCount() {
        const ctx = this.ctx;
        let up = 1; // 涨
        let down = 0; // 跌
        ctx.validate(isBuyCountRule, ctx.query);
        // 买涨查询
        const query_up = {
            where: {
                userTimeStamp: {
                    $between: [toInt(ctx.query.openTime),toInt(ctx.query.closeTime)]
                },
                isBuy: up
            },
        };
        const query_down = {
            where: {
                userTimeStamp: {
                    $between: [toInt(ctx.query.openTime),toInt(ctx.query.closeTime)]
                },
                isBuy: down
            },
        };

        const actions_up = await ctx.model.Action.findAll(query_up);
        let addAmountUp = 0;
        actions_up.forEach(async function (row) {
            addAmountUp = new BigNumber(addAmountUp).plus(new BigNumber(row.amount));// row.amount
        });

        const actions_down = await ctx.model.Action.findAll(query_down);
        let addAmountDown = 0;
        actions_down.forEach(async function (row) {
            addAmountDown = new BigNumber(addAmountDown).plus(new BigNumber(row.amount));
        });
        return {'status_code':200, 'up': addAmountUp, 'down': addAmountDown};
       
    }
}
module.exports = ActionService;